package utils

import (
	"fmt"
	"gitee.com/captials-team/ubdframe/src/common"
	"github.com/jinzhu/copier"
)

// CopyTo 浅拷贝，data=>target
func CopyTo[T interface{}, T1 interface{}](data *T, target *T1) *T1 {
	common.ErrPanic(copier.Copy(target, data))
	return target
}

// CopyMoreTo 浅拷贝数组，data=>target
func CopyMoreTo[T interface{}, T1 interface{}](data []*T, list []*T1) []*T1 {
	for _, v := range data {
		var target = new(T1)
		common.ErrPanic(copier.Copy(target, v))
		list = append(list, target)
	}
	return list
}

// ErrCopyTo 浅拷贝（范围error），data=>target
func ErrCopyTo[T interface{}, T1 interface{}](data *T, target *T1) (*T1, error) {
	return target, copier.Copy(target, data)
}

// LoopHandler 循环处理
func LoopHandler[T interface{}](list []T, h func(T)) {
	for _, v := range list {
		h(v)
	}
}

// ConvertMoreTo 转换为对应的接口（多个进行转换处理）
func ConvertMoreTo[T any, T1 any](list []T, ty []T1) []T1 {
	var ret []T1
	for _, v := range list {
		var a interface{} = v
		ret = append(ret, a.(T1))
	}
	return ret
}

// ErrConvertMoreTo 转换为对应的类型（多个进行转换处理）,返回error
func ErrConvertMoreTo[T any, T1 any](list []T, ty []T1) ([]T1, error) {
	var ret []T1
	for index, v := range list {
		var a interface{} = v
		_, ok := a.(T1)
		if !ok {
			return ret, fmt.Errorf("not support type,index at %d", index)
		}
		ret = append(ret, a.(T1))
	}
	return ret, nil
}

// LookupArray 转换为对应的接口（多个进行转换处理）
func LookupArray[T any](list []T, f func(T, int)) {
	for i, v := range list {
		if f != nil {
			f(v, i)
		}
	}
}

// LookupMap 转换为对应的接口（多个进行转换处理）
func LookupMap[T string | int | int64, T1 any](m map[T]T1, f func(T, T1)) {
	for k, v := range m {
		if f != nil {
			f(k, v)
		}
	}
}
